const Router = require('koa-router');
const query = require('../util/mysql');
const wrapper = require('../util/wrapper');
const checkError = require('../util/checkError');

const router = new Router();

router.prefix('/api/category');

module.exports = router;

/**
 * 获取所有栏目
 */
router.get('/all', async (ctx, next) => {
  const res = await query('select * from category');
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }
  ctx.body = await wrapper(res);
});

/**
 * 获取首页热点栏目
 */
router.get('/hot', async (ctx, next) => {
  const res = await query('select h.*,c.name from category_hot h left join category c on h.cid=c.id limit 3').catch(err => console.log(err));
  if (checkError(res)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }
  ctx.body = await wrapper(res);
});

/**
 * 更新热点栏目
 */
router.post('/hot/edit', async (ctx, next) => {
  const { hot } = ctx.request.body;
  if (!Array.isArray(hot) || hot.length === 0) {
    ctx.body = await wrapper(new Error('缺少参数.'));
    return false;
  }
  for (let i = 0, len = hot.length; i < len; i++) {
    const { id, cid, rank } = hot[i];
    await query(`update category_hot set cid="${cid}",rank="${rank}" where id=${id}`).catch(err => console.log(err));
  }
  ctx.body = await wrapper('更新成功');
});

/**
 * 增加/修改栏目
 */
router.post('/edit', async (ctx, next) => {
  const { list } = ctx.request.body;
  if (!Array.isArray(list) || list.length === 0) {
    ctx.body = await wrapper(new Error('缺少参数.'));
    return false;
  }
  for (let i = 0, len = list.length; i < len; i++) {
    const { id, parent_id, name, rank } = list[i];
    const checkRes = await query(`select * from category where id=${id}`);
    if (checkError(checkRes)) {
      ctx.body = await wrapper(new Error('服务异常.'));
      return false;
    }
    const { name: c_name, parent_id: c_parent_id, rank: c_rank } = checkRes;
    if (checkRes.length === 0) {
      await query(`insert into category(name,parent_id,rank) values('${name}','${parent_id}','${rank}')`).catch(err => console.log(err));
    } else if (c_name !== name || c_parent_id !== parent_id || c_rank !== rank) {
      await query(`update category set name='${name}',parent_id='${parent_id}',rank='${rank}' where id=${id}`).catch(err => console.log(err));
    }
  }
  ctx.body = await wrapper('更新成功');
});

/**
 * 删除栏目
 */
router.post('/del', async (ctx, next) => {
  const { id } = ctx.request.body;
  if (!id) {
    ctx.body = await wrapper(new Error('缺少参数.'));
    return false;
  }

  const delRes = await query(`delete c,a from category c left join article a on c.id=a.cid where c.id=${id}`);
  if (checkError(delRes)) {
    ctx.body = await wrapper(new Error('服务异常.'));
    return false;
  }
  ctx.body = await wrapper('删除成功');
});
